package com.ly.wxstore.comm;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlUtils {
	
	public static void main(String[] args) throws DocumentException {
		String xml="<xml>"
					   +"<return_code><![CDATA[SUCCESS]]></return_code>"
					   +" <return_msg><![CDATA[OK]]></return_msg>"
					   +"<appid><![CDATA[wx2421b1c4370ec43b]]></appid>"
					   +"<mch_id><![CDATA[10000100]]></mch_id>"
					   +"<nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>"
					   +"<sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>"
					   +"<result_code><![CDATA[SUCCESS]]></result_code>"
					   +"<prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>"
					   +"<trade_type><![CDATA[JSAPI]]></trade_type>"
				   +"</xml>";
		System.out.println(toMap(xml));
		
	}
	
	/**
	 * xml to map
	 * @param xml
	 * @return
	 * @throws DocumentException 
	 */
	public static Map<String,String> toMap(String xml) throws DocumentException{
		Document document = DocumentHelper.parseText(xml);
		Element root = document.getRootElement();
		
		Map<String,String> map = new HashMap<String, String>();

        // iterate through child elements of root
        for ( @SuppressWarnings("unchecked")
		Iterator<Element> i = root.elementIterator(); i.hasNext(); ) {
            Element e = i.next();
            map.put(e.getName(), e.getStringValue().replace("<![CDATA[", "").replace("]]>", ""));
        }
		
		return map;
	}

}
